package commons

import (
	"bytes"
	"image"
	"image/color"
	"image/draw"
	"image/jpeg"
	_ "image/png"
	"net/http"
	"time"

	"github.com/sirupsen/logrus"
)

var httpClient = &http.Client{
	Timeout: 30 * time.Second,
	Transport: &http.Transport{
		MaxIdleConns:          10,
		MaxIdleConnsPerHost:   1,
		MaxConnsPerHost:       10,
		IdleConnTimeout:       90 * time.Second,
		TLSHandshakeTimeout:   10 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
	}}

func GetUrlImage(imgUrl, localPath string) image.Image {
	response, err := httpClient.Get(imgUrl)
	if err != nil {
		logrus.Error(GetErrorStack(err, "获取网络图片异常"))
		return nil
	}
	defer response.Body.Close()

	/* reader := bufio.NewReaderSize(response.Body, 8192)
	rawImage, _, err0 := image.Decode(reader) */
	rawImage, _, err0 := image.Decode(response.Body)
	if err0 != nil {
		logrus.Error(GetErrorStack(err0, "非图片格式异常 "+imgUrl))
		return nil
	}
	if rawImage == nil {
		return nil
	}

	jpegBuf := new(bytes.Buffer)
	err2 := jpeg.Encode(jpegBuf, rawImage, nil)
	if err2 != nil {
		return rawImage
	}

	jpegImg, err3 := jpeg.Decode(jpegBuf)
	if err3 != nil {
		return rawImage
	}
	SaveJpeg(localPath, rawImage)

	return jpegImg
}

func imageToJpeg(img image.Image) *bytes.Buffer {
	whiteBackgroundImg := image.NewRGBA(img.Bounds())
	draw.Draw(whiteBackgroundImg, whiteBackgroundImg.Bounds(), &image.Uniform{color.White}, image.Point{}, draw.Src)
	draw.Draw(whiteBackgroundImg, whiteBackgroundImg.Bounds(), img, image.Point{}, draw.Over)
	jpegBuf := new(bytes.Buffer)
	cvtJpegErr := jpeg.Encode(jpegBuf, whiteBackgroundImg, nil)
	if cvtJpegErr != nil {
		logrus.Error(GetErrorStack(cvtJpegErr, "转jpeg格式bytes异常"))
	}
	return jpegBuf
}
